﻿using CommonServiceLocator;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using HandyControl.Controls;
using RemoteTool.Business.Tools;
using RemoteTool.Data;
using RemoteTool.Data.Model;
using RemoteTool.Service;
using System;

namespace RemoteTool.ViewModel.Controls
{
    internal class AddDeviceWindowViewModel : ViewModelBase
    {
        /// <summary>
        /// 关闭窗体
        /// </summary>
        public Action CloseAction { get; set; }
        private DeviceInfo devInfo;
        public DeviceInfo DevInfo { get => devInfo; set { Set(nameof(DevInfo), ref devInfo, value); } }
        public DataService DataService { get; set; }

        public RelayCommand<DeviceInfo> AddDeviceInfo { get; }
        public RelayCommand CloseCmd { get; }

        public AddDeviceWindowViewModel()
        {
            DevInfo = new DeviceInfo();
            DataService = ServiceLocator.Current.GetInstance<DataService>();
            AddDeviceInfo = new RelayCommand<DeviceInfo>(AddDeviceInfoHandler);
            CloseCmd = new RelayCommand(() => { CloseAction?.Invoke(); });
        }

        private async void AddDeviceInfoHandler(DeviceInfo info)
        {
            var main = ServiceLocator.Current.GetInstance<MainViewModel>();
            if (main.IsLogin)
            {
                info.GuidCode = Guid.NewGuid().ToString("N");
                info.CreatorName = main.UserName;
                info.CreateTime = DateTime.Now;
                var webApiService = ServiceLocator.Current.GetInstance<IWebApiService>();
                var result = await webApiService.AddDeviceInfoAsync(info);
                if (result.success)
                {
                    var devInfo = info.ToObjectCopy();
                    Messenger.Default.Send<DeviceInfo>(devInfo, MessageToken.AddDeviceInfo);
                }
                else
                {
                    MessageBox.Show(result.message);
                }
            }
            else
            {
                var devInfo = info.ToObjectCopy();
                devInfo.GuidCode = Guid.NewGuid().ToString("N");
                devInfo.CreatorName= Environment.UserName;
                devInfo.CreateTime = DateTime.Now;
                Messenger.Default.Send<DeviceInfo>(devInfo, MessageToken.AddDeviceInfo);
            }
        }
    }
}
